import java.io.BufferedWriter;
import java.io.FileWriter;
import java.sql.*;
import java.io.*;

public class trans implements Runnable {

	private boolean bExit = false;
	private boolean bExit2 = false;
	static private boolean flag=false;
	static private mythreads [] thr = new mythreads[255];
  public void run() {
        while (!bExit) {
            try { 
        		Thread.sleep ( 1000 ) ;        	 
        	} catch (InterruptedException ie){
        		//catch the signal from main threads or from ctrl+c
        		break;
        	}        	
        }      
        System.out.println("Exit OK");
        
    }
  public trans() {
      Runtime.getRuntime().addShutdownHook(new ExitHandler());
  }
  
  private class ExitHandler extends Thread {
      public ExitHandler() {
          super("Exit Handler");
   }
      
      public void run() {
          System.out.println("Set exit");
          bExit = true;
          try{
        	    if (!bExit2){
        	    	bExit2 = true;
        	    	int i =0;
        	    	while(thr[i]!=null){
        	    		thr[i].stop();       	    		
        	    		
        	    		i++;
        	    	}
        	    	//Thread.sleep(3000);
	        	    File f = new File("my.sql");
		        	if(f.exists())	
		        		f.delete();  
	        	    Connection conn = getConnection();      	 
		            Statement stmt = conn.createStatement();  
		        	System.out.print("ctrc!");
		            BufferedWriter out = new BufferedWriter(new FileWriter("my.sql"));
		            
		            ResultSet res = stmt.executeQuery("select * from logfile");
		            while(res.next()){
		            	out.write(res.getString(1));
		            	out.newLine();
		            } 
		            out.close();
		            
                }
      	}catch (Exception e){
      		//
      		System.out.print(e);
      	}
      	
      }
  }
      
  
  public static void main(String[] args) throws Exception {
	    
     /* Creating and populating table ab */ 
//      -------------This is for teradata-------------
//      try {
//          stmt.execute("DROP table trans");
//          stmt.execute("DROP table acct");
//          stmt.execute("DROP table ticket");
//    	  } catch (SQLException e) {}
//  ---------------------------------------------------    
	  try {
	  Connection conn = getConnection(); 
	  Statement stmt = conn.createStatement(); 
      stmt.execute("DROP table if exists trans ");
      stmt.execute("DROP table if exists acct ");
      stmt.execute("DROP table if exists  ticket ");
      stmt.execute("DROP table if exists  logfile ");
	 
      
//     stmt.execute("CREATE table acct(accountid int not null primary key,ibalance int,balance int)");
//     stmt.execute("Create table trans(tid int not null primary key,trtype int,tracctid int, amount int,transtime timestamp,CONSTRAINT ref1 FOREIGN KEY (tracctid) REFERENCES WITH NO CHECK OPTIoN acct(accountid))" );     
//     stmt.execute("Create table ticket(trcounter int)");
//	  stmt.execute("Create table logfile(logtext varchar(80))");
	 stmt.execute("CREATE table acct(accountid int not null primary key,ibalance int,balance int)");
     stmt.execute("Create table trans(tid int not null primary key,trtype int,tracctid int, amount int,transtime timestamp,CONSTRAINT ref1 FOREIGN KEY (tracctid) REFERENCES acct(accountid))" );     
     stmt.execute("Create table ticket(trcounter int)");
     stmt.execute("Create table logfile(logtext varchar(80))");
     
     trans ctrlc = new trans();
     Thread t = new Thread(ctrlc);
     t.setName("Ctrl C Thread");
     t.start();
     
    
     
	int naccounts=20 ;
	for (int i=1; i<=naccounts;i++){
	stmt.execute("INSERT into acct values("+Integer.toString(i)+",10000,10000)");
	}
	stmt.execute("insert into ticket values(0)");

//	System.out.println("Table Created.");
//        ResultSet res = stmt.executeQuery("SELECT* FROM acct ");
//	while (res.next()){
//	System.out.print("acctid:"+res.getInt(1)+"   ibalance:"+res.getInt(2)+"   balance:"+res.getInt(3)+"\n");
//	} 

    /* Close the connection*/      
      
       
        
	    thr[0] = new mythreads(200, naccounts);  //execute total 500 transaction
        thr[0].start();
        thr[1] = new mythreads(200, naccounts);
        thr[1].start();
        thr[2] = new mythreads(200, naccounts);
        thr[2].start();
        thr[3] = new mythreads(200, naccounts);
        thr[3].start();
        thr[4] = new mythreads(200, naccounts);
        thr[4].start();
        
       
        while(!flag){
        	try { Thread.sleep ( 1000 ) ;
        	} catch (InterruptedException ie){
        		//
        	}
        }
        System.out.print("over!");
        t.interrupt();
        
//        BufferedWriter out = new BufferedWriter(new FileWriter("my.sql"));
//        ResultSet res = stmt.executeQuery("select * from logfile");
//        while(res.next()){
//        	out.write(res.getString(1));
//        	out.newLine();
//        }
        
	  } catch (SQLException e) {System.out.print(e);}
		  
	   catch (Exception e){System.out.print(e);}
        

  }

  public static Connection getConnection() throws Exception {
//    Class.forName("com.ncr.teradata.TeraDriver");
//    String url = "jdbc:teradata://129.7.240.153/database";
	  Class.forName("com.mysql.jdbc.Driver");
	  String url = "jdbc:mysql://localhost/test";
     return DriverManager.getConnection(url, "root", "123qsc");
  }
  public static void goon(){
	  flag=true;
  }
}
